package com.sunfield.baseframe.base;

import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sunfield.baseframe.R;
import com.sunfield.baseframe.http.HttpResult;
import com.sunfield.baseframe.util.ToastUtil;
import com.sunfield.baseframe.view.SwipeBackLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by xiaowogua on 2016/8/15.
 */
public class BaseActivity extends AppCompatActivity {

    protected Toolbar toolbar;
    protected TextView toolbar_title;
    protected ImageView back_button;
    protected LinearLayout ll_head_bg;
    protected View head_status_bar;
    /**
     * 通用的requestCode
     */
    public final int REQUEST_CODE_COMMON = 1024;
    /**
     * 登录
     */
    public static final int REQUEST_CODE_LOGIN = 1025;
    /**
     * 通用的setResult时data的key
     */
    public final String RESULT_KEY = "result";

    protected FrameLayout content_view;

    protected Handler handler;

    private final boolean NOT_PAY = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        super.setContentView(R.layout.my_base_layout);
        if(isSlidingRightBack()){
            SwipeBackLayout sbl = new SwipeBackLayout(this);
            sbl.attachToActivity(this);
        }

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        content_view = (FrameLayout) findViewById(R.id.content_view);

        toolbar_title = (TextView) findViewById(R.id.toolbar_title);
        back_button = (ImageView) findViewById(R.id.back_button);
        ll_head_bg = (LinearLayout) findViewById(R.id.ll_head_bg);
        head_status_bar = findViewById(R.id.head_status_bar);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        head_status_bar.getLayoutParams().height = BaseApplication.statusHeaigh;

        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        handler = new Handler();

        setTitleText(getTitle());
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        LayoutInflater.from(this).inflate(layoutResID, content_view, true);
    }

    @Override
    public void setContentView(View view) {
        content_view.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        if (params == null) {
            params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
        content_view.addView(view, params);
//        if(NOT_PAY){
//            ImageView mark = new ImageView(this);
//            mark.setImageResource(((BaseApplication) BaseApplication.getInstance()).getMark());
//            mark.setAlpha(0.618f);
//            FrameLayout.LayoutParams markParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            markParams.gravity = Gravity.CENTER;
//            content_view.addView(mark, markParams);
//        }
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        content_view.addView(view, params);
    }

    protected void setTitleText(int titleRes) {
        setTitleText(getText(titleRes));
    }

    protected void setTitleText(CharSequence titleText) {
        toolbar_title.setText(titleText);
        ll_head_bg.setVisibility(titleText == null ? View.GONE : View.VISIBLE);
    }

    protected void toast(int msgId) {
        ToastUtil.toast(msgId);
    }

    protected void toast(CharSequence msg) {
        ToastUtil.toast(msg);
    }

    /**
     * 自动收键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (autoHideInput()) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    hideInput();
//                v.clearFocus();
                }
                return super.dispatchTouchEvent(ev);
            }
            // 必不可少，否则所有的组件都不会有TouchEvent了
            if (getWindow().superDispatchTouchEvent(ev)) {
                return true;
            }
            return onTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    protected boolean autoHideInput() {
        return true;
    }

    /**
     * 是否右滑返回
     * @return
     */
    protected boolean isSlidingRightBack(){
        return true;
    }

    /**
     * @param v
     * @param event
     * @return
     * @author wangxl
     * @date 2016-6-7  上午11:14:39
     * @class BaseActivity.java
     * @description 判断是否该收键盘
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    protected InputMethodManager inputMethodManager;

    public void hideInput() {
        if (inputMethodManager == null) {
            inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        }
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public void showInput(View view) {
        view.requestFocus();
        if (inputMethodManager == null) {
            inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        }
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHttpResult(HttpResult result) {

    }

    @Override
    public void onBackPressed() {
        if (mOnBackPressedListener != null && mOnBackPressedListener.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    public interface OnBackPressedListener {
        boolean onBackPressed();
    }

    OnBackPressedListener mOnBackPressedListener;

    public void setOnBackPressedListener(OnBackPressedListener listener) {
        mOnBackPressedListener = listener;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.base_slide_right_out);
    }

    protected boolean checkPermission(String permissionName){
        return PermissionChecker.checkSelfPermission(this, permissionName) == PackageManager.PERMISSION_GRANTED;
    }

    protected void requestPermission(int requestCode, String... permissionName){
        ActivityCompat.requestPermissions(this, permissionName, requestCode);
    }
}
